<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center">
                Edit
            </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-select v-model="form.type" :items="dict['broker_record_type']" item-title="dictName"
                                item-value="dictValue" label="类型" variant="outlined" density="compact"
                                :rules="rules.type" required clearable hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.description" label="描述" variant="outlined" density="compact"
                                :rules="rules.description" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.details" label="详情" variant="outlined" density="compact"
                                :rules="rules.details" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.attachments" label="附件" variant="outlined" density="compact"
                                :rules="rules.attachments" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-select v-model="form.communicationType" :items="dict['communication_type']"
                                item-title="dictName" item-value="dictValue" label="联系方式" variant="outlined"
                                density="compact" :rules="rules.communicationType" clearable hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.duration" label="联系时长" variant="outlined" density="compact"
                                :rules="rules.duration" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.customerId" label="客户" variant="outlined" density="compact"
                                :rules="rules.customerId" required hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.reminderTime" label="提醒时间" type="datetime-local"
                                variant="outlined" density="compact" :rules="rules.reminderTime" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.assignedTo" label="提醒人" variant="outlined" density="compact"
                                :rules="rules.assignedTo" hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.communicationTime" label="联系时间" type="datetime-local"
                                variant="outlined" density="compact" :rules="rules.communicationTime"
                                hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.createTime" label="创建时间" type="datetime-local"
                                variant="outlined" density="compact" :rules="rules.createTime" required
                                hide-details="auto" />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.createBy" label="创建者" variant="outlined" density="compact"
                                :rules="rules.createBy" required hide-details="auto" />
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close">
                    Cancel
                </v-btn>
                <v-btn color="primary" variant="text" :loading="saving" @click="save">
                    Confirm
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import {
    doInsert,
    doUpdate,
    type CustomerRecordModel,
    type ApiResponse
} from '@/api/customer/record/CustmoerRecordManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import { validatorRule } from '@/utils/validateRule';
import { getDictListSync } from '@/utils/dict';


// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const defaultFrom: CustomerRecordModel = {
    type: '',
    description: '',
    details: '',
    attachments: '',
    communicationType: '',
    duration: undefined,
    customerId: '',
    reminderTime: '',
    assignedTo: '',
    communicationTime: '',
    createTime: '',
    createBy: '',
}

// 表单数据
const form = reactive<Partial<CustomerRecordModel>>(defaultFrom);

// 字典数据
const dict = reactive({
    'broker_record_type': [] as any[],
    'communication_type': [] as any[],
});

// 验证规则
const rules = {
    type: [
        (v: any) => !!v || '类型不能为空',
        (v: any) => !v || validatorRule['IS_INTEGER'](v) || '请输入正确的类型',
    ],
    description: [],
    details: [],
    attachments: [],
    communicationType: [],
    duration: [],
    brokerId: [
        (v: any) => !!v || 'broker不能为空',
    ],
    reminderTime: [],
    assignedTo: [],
    communicationTime: [],
    createTime: [
        (v: any) => !!v || '创建时间不能为空',
    ],
    customerId: [
        (v: any) => !!v || '客户不能为空',
    ],
    createBy: [
        (v: any) => !!v || '创建者不能为空',
    ],
};

// 事件发射
const emit = defineEmits<{
    fetchData: [];
}>();

// 显示编辑对话框
function showEdit(row?: CustomerRecordModel) {
    if (!row) {
        title.value = '添加Brokerrecord';
        // 重置表单为默认值
        Object.assign(form, defaultFrom);
    } else {
        title.value = '编辑Brokerrecord';
        // 复制行数据到表单，处理日期格式
        const formData = { ...row };

        // 处理日期字段格式
        if (formData.reminderTime) {
            const date = new Date(formData.reminderTime);
            formData.reminderTime = date.toISOString().slice(0, 16);
        }
        // 处理日期字段格式
        if (formData.communicationTime) {
            const date = new Date(formData.communicationTime);
            formData.communicationTime = date.toISOString().slice(0, 16);
        }

        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, defaultFrom);
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as CustomerRecordModel;
        handlerFormData(submitData);

        let response: ApiResponse<CustomerRecordModel>;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let { msg } = await doUpdate(submitData);
            showSuccess(msg || 'update success');
        } else {
            // 新增模式
            let { msg } = await doInsert(submitData);
            showSuccess(msg || 'add success');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('save failed:', error);
        showError('save failed');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 初始化字典数据
function initDict() {
    dict.broker_record_type = getDictListSync("broker_record_type") || [];
    dict.communication_type = getDictListSync("communication_type") || [];
}

// 暴露方法
defineExpose({
    showEdit,
});

// 生命周期
onMounted(() => {
    initDict();
});
</script>

<style lang="scss" scoped>
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style>